package com.xiaocq.wordskiller;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
	private Context context;
	private Cursor cursor;
	private boolean paging;
	private int count;
	private int index;
	private int displayNum;
	private int showLength;
	private String explains;

	public MyAdapter(Context context, Cursor cursor, boolean paging) {
		this.context = context;
		this.cursor = cursor;
		this.paging = paging;
		this.count = 15;
		this.displayNum = cursor.getCount();
		this.index = 1;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public int getDisplayNum() {
		return displayNum;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public int getCount() {
		if (!paging) {
			return displayNum;
		} else {
			showLength = count * index;
			if (displayNum - showLength < count) {
				return displayNum - showLength;
			} else {
				return count;
			}
		}
	}

	public Object getItem(int position) {
		cursor.moveToPosition(position);
		return cursor;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(R.layout.wrongset_item, null);
			holder = new ViewHolder();
			holder.displayVocabulary = (TextView) convertView
					.findViewById(R.id.wrongset_vocabulary);
			holder.displayExplains = (TextView) convertView
					.findViewById(R.id.wrongset_explains);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if (!paging) {
			cursor.moveToPosition(position);
		} else {
			cursor.moveToPosition(position + showLength);
		}
		holder.displayVocabulary.setText(cursor.getString(1));
		explains = cursor.getString(2);
		explains = explains.replaceAll("\\|", "");
		holder.displayExplains.setText(explains);
		
		return convertView;
	}

	static class ViewHolder {
		TextView displayVocabulary;
		TextView displayExplains;
	}

}
